package com.yb.guigu.pick.auth.listener;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.yb.guigu.pick.auth.bean.dto.request.SysRouteAddInfo;
import com.yb.guigu.pick.auth.entity.SysRole;
import com.yb.guigu.pick.auth.entity.SysRoleRoute;
import com.yb.guigu.pick.auth.entity.SysRoute;
import com.yb.guigu.pick.auth.mapper.SysRoleMapper;
import com.yb.guigu.pick.auth.mapper.SysRoleRouteMapper;
import com.yb.guigu.pick.core.bean.event.GuiguPickEvent;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.event.EventListener;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;

/**
 * Copyright (C), 2022-2023, 姚兵
 * Author: 32210
 * Date: 2023/6/9 15:27
 * FileName: SysUserListener
 * Description:
 */

@Component
@Slf4j
public class SysRouteListener {


    @Autowired
    SysRoleMapper sysRoleMapper;



    @Autowired
    SysRoleRouteMapper sysRoleRouteMapper;

    @EventListener
    @Async
    public void handle(GuiguPickEvent<SysRouteAddInfo> event){
        log.info("accept event:{}",event);
        SysRouteAddInfo sysRouteAddInfo = event.getData();
        SysRoute sysRoute = sysRouteAddInfo.getSysRoute();

        SysRole adminRole = getAdminRole();
        SysRoleRoute sysRoleRoute=new SysRoleRoute();
        sysRoleRoute.setRouteId(sysRoute.getId());
        sysRoleRoute.setRoleId(adminRole.getRoleId());
        sysRoleRoute.setRouteIdPath(sysRoute.getRouteIdPath());
        sysRoleRoute.setCreateTime(LocalDateTime.now());

        sysRoleRouteMapper.insert(sysRoleRoute);

        log.info("event {} processed",event);
    }


    private SysRole getAdminRole(){

        return sysRoleMapper.selectOne(new LambdaQueryWrapper<SysRole>()
                .eq(SysRole::getRoleCode, "admin")
                .select(SysRole::getId, SysRole::getRoleId));
    }
}
